<?php

    class MovieController extends WebController
    {
        public $menu_selected = 'movie';

        /**
        * @return array action filters
        */
        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
                'postOnly + delete', // we only allow deletion via POST request
            );
        }

        /**
        * Specifies the access control rules.
        * This method is used by the 'accessControl' filter.
        * @return array access control rules
        */
        public function accessRules()
        {
            return array(
                array('allow',  // allow all users to perform 'index' and 'view' actions
                    'actions'=>array('index','view', 'watch','search', 'reIndex','test', 'redirect'),
                    'users'=>array('*'),
                ),
                array('deny',  // deny all users
                    'users'=>array('*'),
                ),
            );
        }

        public function actionTest(){
            Yii::import('ext.icurl');

            $s = "http%3A%2F%2Fredirector.googlevideo.com%2Fvideoplayback%3Fid%3Dd25253ddd06197db%26itag%3D5%26source%3Dpicasa%26ip%3D0.0.0.0%26ipbits%3D0%26expire%3D2933730656%26sparams%3Did%2Citag%2Csource%2Cip%2Cipbits%2Cexpire%26signature%3D665AE5B1ADC88491169BA7876917CE05F662FAA5.24F57F74666113EDEC3498C6E3B13CFD845A505%26key%3Dck1";

            $s2 = "http://www.vn-zoom.com/f247/idm-cc-7-3-31-moi-nhat-cho-firefox-17-a-2379349.html";

            $u = urldecode($s2);

            $icurl = new icurl($u);
            $icurl->useAuth = 1;
            $icurl->user = 'daomanhhai85';
            $icurl->pass = 'hhhhhh';
            $icurl->run();
            echo $icurl->body;die;

            echo "<pre>";print_r($icurl->status);echo "<pre>";
            echo "<pre>";print_r($icurl->body);echo "<pre>";
        }

        /**
        * Displays a particular model.
        * @param integer $id the ID of the model to be displayed
        */
        public function actionView($year, $alias, $server = NULL, $part = NULL, $q = 'large', $autostart = 'false')
        {
            //http://wurfl.sourceforge.net/php_index.php
            //            $ua = Yii::app()->session['ua'];
            //            $device = $ua['device'];
            //            $is_mobile = ($device->getCapability('is_tablet') == 'true');
            //            echo "<pre>";print_r($ua['name']);echo "</pre>";
            //            echo "<pre>";print_r($device->getCapability('model_name'));echo "</pre>";
            //            echo $is_mobile ? 'mobile' : 'desktop';
            //            die;

            //if($this->detect->isMobile()){
//                $cs = Yii::app()->getClientScript();
//                $cs->registerScriptFile($this->baseUrl.'/files/js/video-js/video.min.js');
//                $cs->registerCssFile($this->baseUrl.'/files/js/video-js/video-js.min.css');
//                
//                Yii::app()->clientScript->registerScript('video-fluid', "
//  _V_.options.flash.swf = '{$this->baseUrl}/files/js/video-js/video-js.swf';
//  _V_('player').ready(function(){
//    var myPlayer = this;    // Store the video object
//    var aspectRatio = 9/16; // Make up an aspect ratio
//    function resizeVideoJS(){
//      var width = document.getElementById(myPlayer.id).parentElement.offsetWidth;
//      myPlayer.width(width).height( width * aspectRatio );
//    }
//    resizeVideoJS(); // Initialize the function
//    window.onresize = resizeVideoJS; // Call the function on resize
//  });
//                ", CClientScript::POS_END);
                
                
                if(!Yii::app()->request->getQuery('q')) $q = 'medium';
            //}


            $model=Movie::model()->findByAttributes(array('year' => $year, 'alias' => $alias));
            if(!$model) throw new CHttpException(404,'The requested page does not exist.');

            Movie::model()->updateByPk($model->id, array(
                    'view' => $model->view + 1,
                    'view_week' => $model->view_week + 1,
                    'view_month' => $model->view_month + 1,
                ));

            $catIds = array();
            foreach($model->cats as $cat){
                $catIds[] = $cat->id;   
            } 

            $criteria = new CDbCriteria;
            $criteria->distinct = true;
            $criteria->addCondition("t.is_enable = 1");
            $criteria->join = 'LEFT JOIN movie_in_cat ON movie_in_cat.movie_id = t.id';
            $criteria->addCondition("movie_in_cat.cat_id IN(".implode(',', $catIds).")");
            $criteria->limit = 9;


            $catMovies = Movie::model()->findAll($criteria);
            $relatedMovies = array();
            foreach($catMovies as $m){
                if($m->id != $model->id)
                    $relatedMovies[] = $m;
            }
            if(count($relatedMovies) == 9) array_pop($relatedMovies);

            // links & selected link  
            $serverLinks = $model->serverLinks; 

            $selected = array(
                'server' => '',
                'server_alias' => '',
                'name' => '',
                'url' => '',
                'url_redirect' => '',
                'q' => $q,
                'q_name' => '',
                'autostart' => $autostart,
            );
            if($server && $part){
                if(isset($serverLinks[$server]['links'][$part])){
                    $selected['server'] = $serverLinks[$server]['name'];   
                    $selected['server_alias'] = $server;   
                    $selected['name'] = $part;   
                    $selected['url'] = $serverLinks[$server]['links'][$part]['url'];   
                    $selected['url_redirect'] = $serverLinks[$server]['links'][$part]['url_web_qs'][$q]['url_redirect'];   
                    $selected['q_name'] = $serverLinks[$server]['links'][$part]['url_web_qs'][$q]['name'];   
                }
            }
            if(!$selected['url'] && $serverLinks){
                $server = current($serverLinks);
                $selected['server'] = $server['name'];
                $selected['server_alias'] = key($serverLinks);
                $selected['name'] = key($server['links']);
                $link = current($server['links']);
                $selected['url'] = $link['url'];
                $selected['url_redirect'] = $link['url_web_qs'][$q]['url_redirect'];
                $selected['q_name'] = $link['url_web_qs'][$q]['name'];
            }   



            //            echo "<pre>";print_r($serverLinks);echo "</pre>";
            //            echo "<pre>";print_r($selected);echo "</pre>"; die;

//            echo "<pre>";print_r($selected);echo "</pre>";
            if(strpos($selected['url'], 'youtube.com') !== FALSE) $selected['url_redirect'] = $selected['url'];
            $selected['url_dest'] = VideoUrl::_getPicasaweb($selected['url']);

            $this->pageTitle = "Xem phim {$model->nameFull} HD"; 
            $this->pageDesc = $model->desc; 
            
            $this->render('view',array(
                    'model'=>$model,
                    'relatedMovies'=>$relatedMovies,
                    'serverLinks'=>$serverLinks,
                    'selected'=>$selected,
                ));
        }

        public function actionRedirect($year,$alias, $server = NULL, $part = NULL, $url_video = NULL){
            if($url_video){
                $this->redirect(VideoUrl::getUrl($url_video));
            }

            $model=Movie::model()->findByAttributes(array('year' => $year, 'alias' => $alias));
            if(!$model) throw new CHttpException(404,'The requested page does not exist.');

            $serverLinks = $model->serverLinks;
            if(!$serverLinks) throw new CHttpException(404,'The requested page does not exist.');

            if($server && $part){
                if(isset($serverLinks[$server]['links'][$part])){ 
                    $url = $serverLinks[$server]['links'][$part];   
                }
            }

            if(!isset($url)){
                $server = current($serverLinks);
                $url = current($server['links']);
            }

            $media_url = VideoUrl::getUrl($url['url']);

//            echo "<pre>";print_r($url['url']);echo "<pre>";
//            echo "<pre>";print_r($media_url);echo "<pre>";
//            die;
            $this->redirect($media_url);
            //$this->redirect("http://hehe.vn/api/video?url={$url}");
        }



        public function actionIndex($cat_alias=NULL, $country_alias=NULL, $year=NULL, $type=NULL)
        {
            $title = 'Phim mới';
            $this->top_menu = 'new';
            $criteria=new CDbCriteria;
            $criteria->addCondition("t.is_enable = 1");
            $criteria->order = "t.id DESC";
            if($cat_alias){
                $cat = MoviePostCat::model()->findByAttributes(array('alias' => $cat_alias));
                if($cat){
                    $this->top_menu = 'cat';
                    $title = "Phim {$cat->name}";
                    $criteria->join = 'LEFT JOIN movie_in_cat ON movie_in_cat.movie_id = t.id';
                    $criteria->addCondition("movie_in_cat.cat_id = {$cat->id}");
                }   
            }
            if($country_alias){
                $country = MovieCountry::model()->findByAttributes(array('alias' => $country_alias));
                if($country){
                    $this->top_menu = 'country';
                    $title = "Phim {$country->name}";
                    $criteria->addCondition("country_id = {$country->id}");    
                }   
            }
            if($year){
                $this->top_menu = 'home';
                $title = "Phim năm {$year}";
                $criteria->addCondition("`year` = {$year}");    
            }
            if($type=='phim-le'){
                $this->top_menu = 'short';
                $title = "Phim lẻ";
                $criteria->addCondition("`type` = 'SHORT'");  

            }elseif($type=='phim-bo'){
                $this->top_menu = 'series';
                $title = "Phim bộ";
                $criteria->addCondition("`type` = 'SERIES'");

            }elseif($type=='phim-chieu-rap'){
                $this->top_menu = 'cinema';
                $title = "Phim chiếu rạp";
                $criteria->addCondition("`type` = 'SERIES'");

            }elseif($type=='phim-xem-nhieu-nhat'){
                $this->top_menu = 'view';
                $title = "Phim xem nhiều nhất";
                $criteria->order = "`view` DESC";

            }elseif($type=='phim-xem-nhieu-trong-tuan'){
                $this->top_menu = 'view';
                $title = "Phim xem nhiều trong tuần";
                $criteria->order = "`view_week` DESC";

            }elseif($type=='phim-xem-nhieu-trong-thang'){
                $this->top_menu = 'view';
                $title = "Phim xem nhiều trong tháng";
                $criteria->order = "`view_month` DESC";
            }

            $dataProvider = new CActiveDataProvider('Movie', array(
                    'criteria'=>$criteria,
                    'pagination' => array(
                        'pageSize' => 1,
                        'pageVar' => 'page',
                    ),
                ));

            $this->pageTitle = "{$title} | ". $this->siteSlogan;

            $this->render('index', compact('dataProvider', 'title'));
        }

        public function actionSearch($term = NULL, $type=NULL){
            $q = Yii::app()->request->getPost('q');
            $url = $this->createUrl('/movie/movie/search', array('term' => $q, 'type' => 'movie'));
            //echo '<pre>';print_r($url);echo '</pre>';die;
            if($q) $this->redirect($url);

            if(!$term) $this->redirect($this->baseUrl);
            $term = str_replace('-', ' ', $term);
            $term_title = mb_convert_case($term, MB_CASE_TITLE, "UTF-8");

            Yii::import('application.vendors.*');
            require_once('Zend/Search/Lucene.php');
            $indexPath = 'application.runtime.search.movie';


            Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num_CaseInsensitive());
            Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('UTF-8');
            Zend_Search_Lucene::setResultSetLimit(200);

            $index = new Zend_Search_Lucene(Yii::getPathOfAlias($indexPath));


            if($type == 'actor'){
                $title = "Phim có Diễn viên {$term_title} đóng";
                $results = $index->find($term, 
                    'actor', SORT_STRING, SORT_DESC, 
                    'actor_unsigned', SORT_STRING, SORT_DESC  
                );
            }elseif($type == 'director'){
                $title = "Phim do {$term_title} đạo diễn";
                $results = $index->find($term, 
                    'director', SORT_STRING, SORT_DESC, 
                    'director_unsigned', SORT_STRING, SORT_DESC  
                );
            }else{
                $title = "Tìm kiếm {$term_title}";
                $results = $index->find($term 
                    //                    ,'name', SORT_STRING, SORT_DESC
                    //                    ,'name_unsigned', SORT_STRING, SORT_DESC   
                    //                    ,'name_en', SORT_STRING, SORT_DESC
                    //                    ,'name_en_unsigned', SORT_STRING, SORT_DESC
                    //                    ,'desc', SORT_STRING, SORT_DESC  
                    //                    ,'desc_unsigned', SORT_STRING, SORT_DESC
                    //                    ,'content', SORT_STRING, SORT_DESC  
                    //                    ,'content_unsigned', SORT_STRING, SORT_DESC
                    //                    ,'actor', SORT_STRING, SORT_DESC 
                    //                    ,'actor_unsigned', SORT_STRING, SORT_DESC
                    //                    ,'director', SORT_STRING, SORT_DESC 
                    //                    ,'director_unsigned', SORT_STRING, SORT_DESC 
                );
            }


            $this->pageTitle = "{$title} | ". $this->siteName;

            $dataProvider=new CArrayDataProvider($results, array(
                    'pagination'=>array(
                        'pageSize'=>32,
                        'pageVar' => 'page',
                    ),
                ));

            $this->render('index', compact('dataProvider', 'title'));

        }

        public function actionReIndex(){
            Movie::model()->reIndex();
            echo 'All movies were indexed!';
        }  

        /**
        * Returns the data model based on the primary key given in the GET variable.
        * If the data model is not found, an HTTP exception will be raised.
        * @param integer the ID of the model to be loaded
        */
        public function loadModel($id)
        {
            $model=Movie::model()->findByPk($id);
            if($model===null)
                throw new CHttpException(404,'The requested page does not exist.');
            return $model;
        }

    }
